//
// Created by YueChuan on 2023/3/19.
//

#include "connectSocket.h"
connectSocket::connectSocket(int send, int accept) :
        sendUid(send), accUid(accept) {
    port = "1055";
    host = "192.168.117.10";
    socket = new QTcpSocket();
    socket->connectToHost(QHostAddress(host), port.toUShort());
    connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(error_slot(QAbstractSocket::SocketError)));
    connect(socket, SIGNAL(connected()), this, SLOT(connectSucceed()));
    connect(socket, SIGNAL(disconnected()), this, SLOT(disconnectSucceed()));

}

void connectSocket::disconnectSocket() {
    if (socket) {
        socket->disconnectFromHost();
    } else
        return;
}

bool connectSocket::writeToServer(const QString& type, QString data) {

    data = type + "\t" + QString::number(sendUid) + "\t" + QString::number(accUid) + "\t" + data;
    qDebug() << data.toUtf8().data();
    bool oko = socket->write(data.toUtf8().data());
    if (oko) {
        qDebug() << "write succeed";
        return true;
    }
    qDebug() << "write fail";
    return false;
}


// slots---------------
void connectSocket::connectSucceed() {

    qDebug() << "connect succeed";
}

void connectSocket::disconnectSucceed() {
    qDebug() << "disconnectSucceed";
}

void connectSocket::error_slot(QAbstractSocket::SocketError socketError) {
    qDebug() << socketError;
}